package org.oos.services.util;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Random;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.jdom.input.SAXBuilder;
import org.oos.services.OOSException;
import org.w3c.dom.Document;

public class URLUtils
{
	/**
	 * Gets a dom document from the given url.
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public Document retrieve(URL url) throws Exception
	{
		DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		return docBuilder.parse(url.openStream());
	}

	/**
	 * Injects to the given connection the wsse headers.
	 * @param c
	 * @param email
	 * @param authToken
	 * @return
	 * @throws OOSException missing user authorization
	 */
	public URLConnection injectWSSEHeaders(URLConnection c, String email, String authToken) throws OOSException
	{
		if (email==null || authToken==null) throw new OOSException("missing user authorization");
		
		Base64 b64 = new Base64();
		String created = new Long(System.currentTimeMillis()).toString();
		String nonce = (new Long((new Random()).nextLong())).toString();

		String digest = new String(b64.encode(DigestUtils.sha(nonce + created + authToken)));

		c.addRequestProperty("Authorization", "WSSE realm=\"11870.com\", profile=\"UsernameToken\"");
		c.addRequestProperty("X-WSSE", "UsernameToken Username=\"" + email + "\", PasswordDigest=\"" + digest + "\", Nonce=\"" + nonce + "\", Created=\"" + created + "\"");
		return c;
	}

	/**
	 * Gets a dom document from the given url.
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public Document retrieveWSSE(URL url, String email, String authToken) throws Exception
	{
		DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		URLConnection c = url.openConnection();
		c = injectWSSEHeaders(c, email, authToken);
		return docBuilder.parse(c.getInputStream());
	}

	/**
	 * Gets a dom document from the given url.
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public org.jdom.Document retrieveJDomWSSE(URL url, String email, String authToken) throws Exception
	{
		SAXBuilder parser = new SAXBuilder();
		URLConnection c = url.openConnection();
		c = injectWSSEHeaders(c, email, authToken);
		return parser.build(c.getInputStream());
	}

	/**
	 * Gets a dom document from the given url.
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public org.jdom.Document retrieveJDom(URL url) throws Exception
	{
		SAXBuilder parser = new SAXBuilder();
		URLConnection c = url.openConnection();
		return parser.build(c.getInputStream());
	}
}
